package cn.learn.office.excel_v2.sort;


import cn.learn.office.excel_v2.ExportExcelUtil;
import cn.learn.office.excel_v2.ExportExcelVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 有实体类的属性并且输入Excel表导出顺序的类
 *
 * @author huangyezhan
 * @version 2.0
 * @date 2020年4月20日21:17:17
 */
public class DomainCustomSort implements HandlerColumnSort {

    @Override
    public void columnSort(ExportExcelVo excelVo, Sheet sheet, Map<ExportExcelVo.Position, CellStyle> createStyleInstance) {
        List columns = excelVo.getList();
        //开始导入数据开始行数号（去掉表头的行数）
        int startRowNum = excelVo.getHeadRowNum();
        try {
            Field[] fields = columns.get(0).getClass().getDeclaredFields();
            Row     row    = null;
            Cell    cell   = null;
            for (int i = 0; i < columns.size(); i++) {
                row = sheet.createRow(i + startRowNum);
                Object o = columns.get(i);
                //跟标题列数保持一样长度
                for (int j = 0; j < excelVo.getColumnNum(); j++) {
                    String fieldName = excelVo.getHeadSort()[j];
                    cell = row.createCell(j);
                    for (Field field : fields) {
                        if (field.getName().equalsIgnoreCase(fieldName)) {
                            field.setAccessible(true);
                            Object o1 = field.get(o);
                            ExportExcelUtil.fillDatabyRealType(createStyleInstance, o1, cell);
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
